<?php require('pre.inc'); ?>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script id="run" src="js/bgraph.js"></script>	
<h1>Linked Open Aalto Data on a map</h1>
<p id="load" style="display: inherit;">Loading <img src="load.gif" alt="Loading ..."/></p>
<style type="text/css">
div.inline { float:left; }
.clearBoth { clear:both; }
</style>

<div id="stats">
<p>This map queries the Aalto University buildings located in Otaniemi and visualizes some details about located the departments when building is selected. <i>CLICK A? BUILDING!</i></p>	
<div id="map-canvas" style="width: 800px; height: 600px"><img src="load.gif" alt="loading ..."/></div>
<!--<p>Total number of triples: <span id="triples"><img src="load.gif" alt="loading ..."/></span></p> -->
</div>

<script>
google.load("visualization", "1", {packages:["corechart","charteditor"]});
google.setOnLoadCallback(function() {
 $('#load').css("display", "none");
});
	
var bgraph = new BGraph();	
var prefix = bgraph.getPrefixes();
var map;
var infoWindow;
var image = ''
var cCount = 1554;
var dCount = 1554;

var q1 = prefix+
"SELECT ?building ?label ?lat ?long (GROUP_CONCAT(DISTINCT ?name; SEPARATOR=',') AS ?departments) (GROUP_CONCAT(DISTINCT ?homepage; SEPARATOR=',') AS ?homepages) (COUNT(?course) AS ?count) WHERE {"+
"?building geo:lat ?lat ."+
"?building db-owl:address ?label ."+
"?building geo:long ?long ."+
"?building vcard:region ?region ."+
"?department tisc:locatedAt ?building ."+
"?department aiiso:code ?code ."+
"?department rdfs:label ?deplabel ."+
"?department foaf:homepage ?homepage ."+
"?NOPPAdepartment aiiso:code ?code ."+
"?NOPPAdepartment foaf:name ?name ."+
"?NOPPAdepartment aiiso:teaches ?course ."+
"FILTER(?region = 'Espoo')"+
"FILTER(lang(?name) = 'en')"+
"} GROUP BY ?building ?lat ?long ?label";

var q2 = prefix+"SELECT (count(DISTINCT ?course) as ?dCount) (count(?course) as ?count) where { ?course teach:arrangedAt [ical:dtstart ?start].}";

function initialize() {
  var mapDiv = document.getElementById('map-canvas');
  map = new google.maps.Map(mapDiv, {
    center: new google.maps.LatLng(60.186389, 24.827642),
    zoom: 14,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  infoWindow = new google.maps.InfoWindow();
  google.maps.event.addListenerOnce(map, 'tilesloaded', plotMap(q1,"#map-canvas"));

}

function ajaxQuery(q) {
	return $.ajax({url: "http://data.aalto.fi/sparql?query="+encodeURIComponent(q)+"&format=json"});
}

function getCCount(queryString) {
	ajaxQuery(queryString).done(function(data) {
	//FIXME: Next line is for debugging only
	//data = $.parseJSON(data);
	if(data.results.bindings.length>0) {
		cCount = data.results.bindings[0]["count"].value
		dCount = data.results.bindings[0]["dCount"].value
	} else { console.log("Couldnt load cCount, assuming 1554 ..."); }
	});
}

initialize();
getCCount(q2);


function plotMonthly(building) {
	
var bq = prefix+"SELECT xsd:string(?month) (count(?course) as ?lectures) where { ?department tisc:locatedAt <"+building+"> ; aiiso:code ?code . ?NOPPAdepartment aiiso:code ?code . ?NOPPAdepartment aiiso:teaches ?course . ?course teach:arrangedAt [ical:dtstart ?start].} GROUP BY (substr(str(?start),6,2) as ?month) ORDER BY ?month";
	
ajaxQuery(bq).done(function(data) {
	//FIXME: Next line is for debugging only
	//data = $.parseJSON(data);
if(data.results.bindings.length>0) {

var gData = bgraph.SparqlJSON2GoogleJSON(data);
var data = new google.visualization.DataTable(gData);
var months = [ "01", "02", "03", "04", "05", "06","07", "08", "09", "10", "11", "12" ];

for(var i=0;i<data.getNumberOfRows();i++)
  {
	var row = data.getValue(i,0);
	var pMonth = parseInt(row,10);
	 
     // IF some month is missing add new row
     if(i+1 != pMonth) {
        data.insertRows(i,1);
        data.setValue(i,0,months[i]);
        data.setValue(i,1,0);
       }
	else data.setValue(i,0,months[i]);
}

// IF months missing from the end of the table
while(data.getNumberOfRows()<12) {
      data.addRow([months[data.getNumberOfRows()], 0]);
}


var viz = new google.visualization.LineChart($("#"+building.replace(/[^\w\s]/gi, ''))[0]);

options ={
		hAxis:  {title: 'Number of lectures',  showTextEvery: 1},
        vAxis: {title: 'Month',viewWindowMode: "explicit", viewWindow:{ min: 0 }},
		legend:"none",
		useFormatFromData:true,
		viewWindowMode:"pretty",
		curveType:"function",
		lineWidth:2,
		theme:"maximized",
		width: 280,
		height: 150,
}

		
viz.draw(data,options);

}
});
}

function createMarker(map, position, value, building) {
    var marker = new google.maps.Marker({
      position: position,
      map: map,
      icon: image
    });

    google.maps.event.addListener(marker, 'click', function() {
	  infoWindow.close();
      infoWindow = new google.maps.InfoWindow();
	  infoWindow.setContent(value);
      infoWindow.open(map, marker);
      
      var foo = true;
	  google.maps.event.addListener(infoWindow, 'domready', function() {
		if(foo) { plotMonthly(building); foo = false; }
	   });
		
    });
    

    
    
  }

function plotMap(queryString,elem) {
	ajaxQuery(queryString).done(function(data) {
	 //FIXME
	// data = $.parseJSON(data); // For debugging only
	if(data.results.bindings.length>0) {
		
		var bindings = data.results.bindings;
		
		//var gTable = new google.visualization.DataTable(bgraph.SparqlJSON2GoogleJSON(data));
		//console.log(gTable.toJSON());
		
		for(result in bindings) {
		
		var latLng = new google.maps.LatLng(bindings[result]["lat"].value,bindings[result]["long"].value);	
		var homepages = (bindings[result]["homepages"].value).split(",");
		var departments = (bindings[result]["departments"].value).split(",");
		
		for(i=0;i<homepages.length;i++) homepages[i] = "<a href='"+homepages[i]+"' target='_blank'>"+departments[i]+"</a>"
        
		var html = "<div style='font-size: 10px; width:300px;overflow:hidden;'><b>"+bindings[result]["label"].value+"</b><br/>";
		html+="<p>";
		html+=homepages.join("<br/>");
		html+="</p><p><h2>Statistics of the department(s) in this building:</h2>"+(bindings[result]["count"].value)+" courses offered, "+((parseInt(bindings[result]["count"].value)/dCount)*100).toFixed(2)+"% of all of the courses.<br/>Number of lectures through the year:</p>";
		html+="</div><div style='height:180px; overflow:hidden;' id="+(bindings[result]["building"].value).replace(/[^\w\s]/gi, '')+"><img src='load.gif' alt='loading ...'/></div>";
		createMarker(map,latLng,html,bindings[result]["building"].value)

		}
	} else $(elem).html("No results found");
	});
}

</script>

<?php require('post.inc'); ?>

